﻿using System.IO;
using System.Linq;
using System.Xml.Linq;
using Ionic.Zip;

namespace Smarly.Idml
{
	public class IdmlBuilder
	{
		private const string TempFolder = @"d:\temp\_idml";
		private const string TemplateFile = @"D:\Work\Smarly\sources\Smarly.Idml\smarly.idml";
		private static readonly object _lock = new object();

		public static string CreateFile(XElement[] texts)
		{
			const string resultFile = @"d:\smarly.idml";
			lock (_lock)
			{
				if (Directory.Exists(TempFolder))
					Directory.Delete(TempFolder, true);

				Directory.CreateDirectory(TempFolder);

				if (File.Exists(resultFile))
					File.Delete(resultFile);

				using (var zip = new ZipFile(TemplateFile))
				{
					zip.ExtractAll(TempFolder);
				}

				UpdateContent(texts);

				using (var zip = new ZipFile())
				{
					zip.AddDirectory(TempFolder);
					zip.Save(resultFile);
				}

				return resultFile;
			}
		}

		private static void UpdateContent(XElement[] texts)
		{
			string storyXml = TempFolder + @"\Stories\Story_uee.xml";
			XDocument doc = XDocument.Load(storyXml);
			doc.Root.Descendants("ParagraphStyleRange").ToList().Remove();

			doc.Root.Descendants("Story").Single().Add( /*StoryElement(texts)*/texts);

			doc.Save(storyXml);
		}
	}
}